﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Sinacor.Infra.UI.Controls.SmartClient;
using Sinacor.Infra.UI.Controls.SmartClient.Validation;
using System.Collections.ObjectModel;
using Sinacor.Infra.UI.Controls.SmartClient.BehaviorPolicy;
using System.Globalization;

namespace Sinacor.Infra.UI.Controls.SmartClient
{
    public enum SelectionComboType
    {
        CPF,
        CNPJ,
        CVM,
        ClienteEstrangeiro,
        Outros
    }

    public partial class SinacorIdentificadorInvestidor : Control, IValidatableObject, IVisibilityBehaviorPolicy, IBehaviorPolicyObject
    {
        Binding externalCPFBinding;
        Binding externalCVMBinding;
        Binding externalCNPJBinding;
        Binding externalClienteEstrangeiroBinding;
        Binding externalOutrosBinding;
        SinacorCnpjTextBox txtCNPJ;
        SinacorCpfTextBox txtCPF;
        SinacorCvmTextBox txtCVM;
        SinacorInvestidorEstrangeiroTextBox txtClienteEstrangeiro;
        SinacorFilteredTextBox txtOutros;
        SinacorComboBox cbControlSelector;

        SinacorComboBoxItem ClienteEstrangeiro;
        SinacorComboBoxItem CVM;
        SinacorComboBoxItem CPF;
        SinacorComboBoxItem CNPJ;
        SinacorComboBoxItem Outros;

        public SinacorIdentificadorInvestidor()
        {
            ValidationManager.InitializeValidation(this);
            this.BehaviorPolicyAdapter = new BehaviorPolicyAdapter(this);

            this.Loaded += new RoutedEventHandler(SinacorIdentificadorInvestidor_Loaded);

            ClienteEstrangeiro = new SinacorComboBoxItem();
            ClienteEstrangeiro.SetResourceReference(ComboBoxItem.ContentProperty, "Infra.Controls.Label.ClienteEstrangeiro");
            ClienteEstrangeiro.Name = "cbItemClienteEstrangeiro";

            CVM = new SinacorComboBoxItem();
            CVM.SetResourceReference(ComboBoxItem.ContentProperty, "Infra.Controls.Label.CVM");
            CVM.Name = "cbItemCVM";

            CPF = new SinacorComboBoxItem();
            CPF.SetResourceReference(ComboBoxItem.ContentProperty, "Infra.Controls.Label.CPF");
            CPF.Name = "cbItemCPF";

            CNPJ = new SinacorComboBoxItem();
            CNPJ.SetResourceReference(ComboBoxItem.ContentProperty, "Infra.Controls.Label.CNPJ");
            CNPJ.Name = "cbItemCNPJ";

            Outros = new SinacorComboBoxItem();
            Outros.SetResourceReference(ComboBoxItem.ContentProperty, "Infra.Controls.Label.Outros");
            Outros.Name = "cbItemOutros";
        }

        //private const string CpfValidationRuleName = "CpfValidationRule";
        //private const string CnpjValidationRuleName = "CnpjValidationRule";
        //private const string CvmValidationRuleName = "CvmValidationRule";
        //private const string InvestidorEstrangeiroValidationRuleName = "InvestidorEstrangeiroValidationRule";
        //private const string RequiredValidationRuleName = "RequiredValidator";

        private BehaviorPolicyAdapter _behaviorPolicyAdapter;
        private static readonly DependencyProperty InternalClienteEstrangeiroValueProperty = DependencyProperty.Register("InternalClienteEstrangeiroValue", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        private static readonly DependencyProperty InternalCVMValueProperty = DependencyProperty.Register("InternalCVMValue", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        private static readonly DependencyProperty InternalCNPJValueProperty = DependencyProperty.Register("InternalCNPJValue", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        private static readonly DependencyProperty InternalOutrosValueProperty = DependencyProperty.Register("InternalOutrosValue", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        private static readonly DependencyProperty InternalCPFValueProperty = DependencyProperty.Register("InternalCPFValue", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty InvalidCpfErrorMessageProperty = DependencyProperty.Register("InvalidCpfErrorMessage", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("Infra.Controls.Message.CpfInvalido"));
        public static readonly DependencyProperty InvalidCnpjErrorMessageProperty = DependencyProperty.Register("InvalidCnpjErrorMessage", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("Infra.Controls.Message.CnpjInvalido"));
        public static readonly DependencyProperty InvalidCvmErrorMessageProperty = DependencyProperty.Register("InvalidCvmErrorMessage", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("Infra.Controls.Message.CvmInvalido"));
        public static readonly DependencyProperty InvalidClienteEstrangeiroErrorMessageProperty = DependencyProperty.Register("InvalidClienteEstrangeiroErrorMessage", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("Infra.Controls.Message.ClienteEstrangeiroInvalido"));
        public static readonly DependencyProperty ShowCPFProperty = DependencyProperty.Register("ShowCPF", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false, ShowCPFPropertyChanged));
        public static readonly DependencyProperty ShowCVMProperty = DependencyProperty.Register("ShowCVM", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false, ShowCVMPropertyChanged));
        public static readonly DependencyProperty ShowClienteEstrangeiroProperty = DependencyProperty.Register("ShowClienteEstrangeiro", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false, ShowClienteEstrangeiroPropertyChanged));
        public static readonly DependencyProperty ShowCNPJProperty = DependencyProperty.Register("ShowCNPJ", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false, ShowCNPJPropertyChanged));
        public static readonly DependencyProperty ShowOutrosProperty = DependencyProperty.Register("ShowOutros", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false, ShowOutrosPropertyChanged));

        public static readonly DependencyProperty CPFBindProperty = DependencyProperty.Register("CPFBind", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty CNPJBindProperty = DependencyProperty.Register("CNPJBind", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty CVMBindProperty = DependencyProperty.Register("CVMBind", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty ClienteEstrangeiroBindProperty = DependencyProperty.Register("ClienteEstrangeiroBind", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty OutrosBindProperty = DependencyProperty.Register("OutrosBind", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public static readonly DependencyProperty PolicyNameProperty = DependencyProperty.Register("PolicyName", typeof(string), typeof(SinacorIdentificadorInvestidor));
        public static readonly DependencyProperty ComboSelectionProperty = DependencyProperty.Register("ComboSelection", typeof(SelectionComboType?), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(null, ComboSelectionChanged));
        public static readonly DependencyProperty RequiredErrorMessageProperty = DependencyProperty.Register("RequiredErrorMessage", typeof(string), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata("Infra.Controls.Message.CampoObrigatorio"));
        public static readonly DependencyProperty IsRequiredProperty = DependencyProperty.Register("IsRequired", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));

        public static readonly DependencyProperty IsCpfReadOnlyProperty = DependencyProperty.Register("IsCpfReadOnly", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));
        public static readonly DependencyProperty IsCnpjReadOnlyProperty = DependencyProperty.Register("IsCnpjReadOnly", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));
        public static readonly DependencyProperty IsCvmReadOnlyProperty = DependencyProperty.Register("IsCvmReadOnly", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));
        public static readonly DependencyProperty IsClienteEstrangeiroReadOnlyProperty = DependencyProperty.Register("IsClienteEstrangeiroReadOnly", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));
        public static readonly DependencyProperty IsOutrosReadOnlyProperty = DependencyProperty.Register("IsOutrosReadOnly", typeof(bool), typeof(SinacorIdentificadorInvestidor), new FrameworkPropertyMetadata(false));

        //static void IsCpfReadOnlyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        //{
        //    SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
        //    if (instance != null)
        //        instance.txtCPF.IsReadOnly = instance.IsCpfReadOnly;
        //}
        //static void IsCnpjReadOnlyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        //{
        //    SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
        //    if (instance != null)
        //        instance.txtCNPJ.IsReadOnly = instance.IsCnpjReadOnly;
        //}
        //static void IsCvmReadOnlyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        //{
        //    SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
        //    if (instance != null)
        //        instance.txtCVM.IsReadOnly = instance.IsCvmReadOnly;
        //}
        //static void IsClienteEstrangeiroReadOnlyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        //{
        //    SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
        //    if (instance != null)
        //        instance.txtClienteEstrangeiro.IsReadOnly = instance.IsClienteEstrangeiroReadOnly;
        //}
        //static void IsOutrosReadOnlyPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        //{
        //    SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
        //    if (instance != null)
        //        instance.txtOutros.IsReadOnly = instance.IsOutrosReadOnly;
        //}

        static void ComboSelectionChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;

            if (instance != null && instance.cbControlSelector != null)
            {
                switch (instance.ComboSelection)
                {
                    case SelectionComboType.CPF:
                        instance.cbControlSelector.SelectedItem = instance.CPF;
                        break;
                    case SelectionComboType.CNPJ:
                        instance.cbControlSelector.SelectedItem = instance.CNPJ;
                        break;
                    case SelectionComboType.CVM:
                        instance.cbControlSelector.SelectedItem = instance.CVM;
                        break;
                    case SelectionComboType.ClienteEstrangeiro:
                        instance.cbControlSelector.SelectedItem = instance.ClienteEstrangeiro;
                        break;
                    case SelectionComboType.Outros:
                        instance.cbControlSelector.SelectedItem = instance.Outros;
                        break;
                    default:
                        instance.cbControlSelector.SelectedIndex = -1;
                        break;
                }
            }
        }

        static void ShowCPFPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
            if (instance != null && instance.cbControlSelector != null)
            {
                if (instance.ShowCPF)
                {
                    if (!instance.cbControlSelector.Items.Contains(instance.CPF))
                        instance.cbControlSelector.Items.Add(instance.CPF);
                }
                else
                {
                    if (instance.cbControlSelector.Items.Contains(instance.CPF))
                        instance.cbControlSelector.Items.Remove(instance.CPF);
                }
            }
        }
        static void ShowClienteEstrangeiroPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
            if (instance != null && instance.cbControlSelector != null)
            {
                if (instance.ShowClienteEstrangeiro)
                {
                    if (!instance.cbControlSelector.Items.Contains(instance.ClienteEstrangeiro))
                        instance.cbControlSelector.Items.Add(instance.ClienteEstrangeiro);
                }
                else
                {
                    if (instance.cbControlSelector.Items.Contains(instance.ClienteEstrangeiro))
                        instance.cbControlSelector.Items.Remove(instance.ClienteEstrangeiro);
                }
            }
        }
        static void ShowCVMPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
            if (instance != null && instance.cbControlSelector != null)
            {
                if (instance.ShowCVM)
                {
                    if (!instance.cbControlSelector.Items.Contains(instance.CVM))
                        instance.cbControlSelector.Items.Add(instance.CVM);
                }
                else
                {
                    if (instance.cbControlSelector.Items.Contains(instance.CVM))
                        instance.cbControlSelector.Items.Remove(instance.CVM);
                }
            }
        }
        static void ShowCNPJPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
            if (instance != null && instance.cbControlSelector != null)
            {
                if (instance.ShowCNPJ)
                {
                    if (!instance.cbControlSelector.Items.Contains(instance.CNPJ))
                        instance.cbControlSelector.Items.Add(instance.CNPJ);
                }
                else
                {
                    if (instance.cbControlSelector.Items.Contains(instance.CNPJ))
                        instance.cbControlSelector.Items.Remove(instance.CNPJ);
                }
            }
        }
        static void ShowOutrosPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            SinacorIdentificadorInvestidor instance = obj as SinacorIdentificadorInvestidor;
            if (instance != null && instance.cbControlSelector != null)
            {
                if (instance.ShowOutros)
                {
                    if (!instance.cbControlSelector.Items.Contains(instance.Outros))
                        instance.cbControlSelector.Items.Add(instance.Outros);
                }
                else
                {
                    if (instance.cbControlSelector.Items.Contains(instance.Outros))
                        instance.cbControlSelector.Items.Remove(instance.Outros);
                }
            }
        }

        public bool IsRequired
        {
            get { return (bool)GetValue(IsRequiredProperty); }
            set { SetValue(IsRequiredProperty, value); }
        }

        public string RequiredErrorMessage
        {
            get { return (string)GetValue(RequiredErrorMessageProperty); }
            set { SetValue(RequiredErrorMessageProperty, value); }
        }

        public SelectionComboType? ComboSelection
        {
            get { return (SelectionComboType?)GetValue(ComboSelectionProperty); }
            set { SetValue(ComboSelectionProperty, value); }
        }

        internal BehaviorPolicyAdapter BehaviorPolicyAdapter
        {
            get { return _behaviorPolicyAdapter; }
            set { _behaviorPolicyAdapter = value; }
        }

        string InternalClienteEstrangeiroValue
        {
            get { return (string)GetValue(InternalClienteEstrangeiroValueProperty); }
            set { SetValue(InternalClienteEstrangeiroValueProperty, value); }
        }

        string InternalCVMValue
        {
            get { return (string)GetValue(InternalCVMValueProperty); }
            set { SetValue(InternalCVMValueProperty, value); }
        }

        string InternalCNPJValue
        {
            get { return (string)GetValue(InternalCNPJValueProperty); }
            set { SetValue(InternalCNPJValueProperty, value); }
        }

        string InternalOutrosValue
        {
            get { return (string)GetValue(InternalOutrosValueProperty); }
            set { SetValue(InternalOutrosValueProperty, value); }
        }

        string InternalCPFValue
        {
            get { return (string)GetValue(InternalCPFValueProperty); }
            set { SetValue(InternalCPFValueProperty, value); }
        }

        public string InvalidCpfErrorMessage
        {
            get { return (string)GetValue(InvalidCpfErrorMessageProperty); }
            set { SetValue(InvalidCpfErrorMessageProperty, value); }
        }

        public string InvalidCnpjErrorMessage
        {
            get { return (string)GetValue(InvalidCnpjErrorMessageProperty); }
            set { SetValue(InvalidCnpjErrorMessageProperty, value); }
        }

        public string InvalidCvmErrorMessage
        {
            get { return (string)GetValue(InvalidCvmErrorMessageProperty); }
            set { SetValue(InvalidCvmErrorMessageProperty, value); }
        }

        public string InvalidClienteEstrangeioErrorMessage
        {
            get { return (string)GetValue(InvalidClienteEstrangeiroErrorMessageProperty); }
            set { SetValue(InvalidClienteEstrangeiroErrorMessageProperty, value); }
        }

        public bool ShowCPF
        {
            get { return (bool)GetValue(ShowCPFProperty); }
            set { SetValue(ShowCPFProperty, value); }
        }
        public bool ShowCVM
        {
            get { return (bool)GetValue(ShowCVMProperty); }
            set { SetValue(ShowCVMProperty, value); }
        }
        public bool ShowClienteEstrangeiro
        {
            get { return (bool)GetValue(ShowClienteEstrangeiroProperty); }
            set { SetValue(ShowClienteEstrangeiroProperty, value); }
        }
        public bool ShowCNPJ
        {
            get { return (bool)GetValue(ShowCNPJProperty); }
            set { SetValue(ShowCNPJProperty, value); }
        }
        public bool ShowOutros
        {
            get { return (bool)GetValue(ShowOutrosProperty); }
            set { SetValue(ShowOutrosProperty, value); }
        }

        public string CPFBind
        {
            get { return (string)GetValue(CPFBindProperty); }
            set { SetValue(CPFBindProperty, value); }
        }
        public string CNPJBind
        {
            get { return (string)GetValue(CNPJBindProperty); }
            set { SetValue(CNPJBindProperty, value); }
        }
        public string CVMBind
        {
            get { return (string)GetValue(CVMBindProperty); }
            set { SetValue(CVMBindProperty, value); }
        }
        public string ClienteEstrangeiroBind
        {
            get { return (string)GetValue(ClienteEstrangeiroBindProperty); }
            set { SetValue(ClienteEstrangeiroBindProperty, value); }

        }
        public string OutrosBind
        {
            get { return (string)GetValue(OutrosBindProperty); }
            set { SetValue(OutrosBindProperty, value); }
        }

        public bool IsCpfReadOnly
        {
            get { return (bool)GetValue(IsCpfReadOnlyProperty); }
            set { SetValue(IsCpfReadOnlyProperty, value); }
        }
        public bool IsCnpjReadOnly
        {
            get { return (bool)GetValue(IsCnpjReadOnlyProperty); }
            set { SetValue(IsCnpjReadOnlyProperty, value); }
        }
        public bool IsCvmReadOnly
        {
            get { return (bool)GetValue(IsCvmReadOnlyProperty); }
            set { SetValue(IsCvmReadOnlyProperty, value); }
        }
        public bool IsClienteEstrangeiroReadOnly
        {
            get { return (bool)GetValue(IsClienteEstrangeiroReadOnlyProperty); }
            set { SetValue(IsClienteEstrangeiroReadOnlyProperty, value); }
        }
        public bool IsOutrosReadOnly
        {
            get { return (bool)GetValue(IsOutrosReadOnlyProperty); }
            set { SetValue(IsOutrosReadOnlyProperty, value); }
        }

        void SinacorIdentificadorInvestidor_Loaded(object sender, RoutedEventArgs e)
        {
            if (externalCPFBinding == null)
                externalCPFBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CPFBindProperty);
            if (externalCVMBinding == null)
                externalCVMBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CVMBindProperty);
            if (externalCNPJBinding == null)
                externalCNPJBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CNPJBindProperty);
            if (externalOutrosBinding == null)
                externalOutrosBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.OutrosBindProperty);
            if (externalClienteEstrangeiroBinding == null)
                externalClienteEstrangeiroBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.ClienteEstrangeiroBindProperty);
        }

        //protected void CreateValidations()
        //{
        //    if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
        //        return;

        //    if (!this.txtCPF.ValidationRules.Contains(CpfValidationRuleName) && ShowCPF)
        //    {
        //        CpfValidationRule CpfValidation = new CpfValidationRule(this, SinacorIdentificadorInvestidor.InternalCPFValueProperty);
        //        CpfValidation.Name = CpfValidationRuleName;

        //        this.txtCPF.ValidationRules.Add(CpfValidation);
        //        CpfValidation.ErrorContent = this.InvalidCpfErrorMessage;
        //        CpfValidation.IsEnabled = true;
        //    }

        //    if (!this.txtCNPJ.ValidationRules.Contains(CnpjValidationRuleName) && ShowCNPJ)
        //    {
        //        CnpjValidationRule CnpjValidation = new CnpjValidationRule(this, SinacorIdentificadorInvestidor.InternalCNPJValueProperty);
        //        CnpjValidation.Name = CnpjValidationRuleName;

        //        this.txtCNPJ.ValidationRules.Add(CnpjValidation);
        //        CnpjValidation.ErrorContent = this.InvalidCnpjErrorMessage;
        //        CnpjValidation.IsEnabled = true;
        //    }

        //    if (!this.txtCVM.ValidationRules.Contains(CvmValidationRuleName) && ShowCVM)
        //    {
        //        CvmValidationRule CvmValidation = new CvmValidationRule(this, SinacorIdentificadorInvestidor.InternalCVMValueProperty);
        //        CvmValidation.Name = CvmValidationRuleName;

        //        this.txtCVM.ValidationRules.Add(CvmValidation);
        //        CvmValidation.ErrorContent = this.InvalidCvmErrorMessage;
        //        CvmValidation.IsEnabled = true;
        //    }
        //    if (!this.txtClienteEstrangeiro.ValidationRules.Contains(InvestidorEstrangeiroValidationRuleName) && ShowClienteEstrangeiro)
        //    {
        //        InvestidorEstrangeiroValidationRule InvEstrangeiroValidation = new InvestidorEstrangeiroValidationRule(this, SinacorIdentificadorInvestidor.InternalClienteEstrangeiroValueProperty);
        //        InvEstrangeiroValidation.Name = InvestidorEstrangeiroValidationRuleName;

        //        this.txtClienteEstrangeiro.ValidationRules.Add(InvEstrangeiroValidation);
        //        InvEstrangeiroValidation.ErrorContent = this.InvalidClienteEstrangeioErrorMessage;
        //        InvEstrangeiroValidation.IsEnabled = true;
        //    }
        //}

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            cbControlSelector = this.GetTemplateChild("cbControlSelector") as SinacorComboBox;
            if (ShowClienteEstrangeiro)
            {
                cbControlSelector.Items.Add(ClienteEstrangeiro);
            }
            if (ShowCVM)
            {
                cbControlSelector.Items.Add(CVM);
            }
            if (ShowCPF)
            {
                cbControlSelector.Items.Add(CPF);
            }
            if (ShowCNPJ)
            {
                cbControlSelector.Items.Add(CNPJ);
            }
            if (ShowOutros)
            {
                cbControlSelector.Items.Add(Outros);
            }

            /*
             * AutoFill setado pra false, para não adicionar 0 nos controles gerando CPF's e CNPJ's inválidos,
             * afinal, esses documentos têm os valores calculados e são validados pelo dígito verificador
             * dessa forma, eles não podem receber zeros a esquerda
             * 
             */
            txtCNPJ = this.GetTemplateChild("txtCNPJ") as SinacorCnpjTextBox;
            txtCNPJ.AutoFill = false;
            txtCPF = this.GetTemplateChild("txtCPF") as SinacorCpfTextBox;
            txtCPF.AutoFill = false;
            txtCVM = this.GetTemplateChild("txtCVM") as SinacorCvmTextBox;
            txtCVM.AutoFill = false;
            txtClienteEstrangeiro = this.GetTemplateChild("txtClienteEstrangeiro") as SinacorInvestidorEstrangeiroTextBox;
            txtClienteEstrangeiro.AutoFill = false;
            txtOutros = this.GetTemplateChild("txtOutros") as SinacorFilteredTextBox;

            if (ComboSelection.HasValue)
                foreach (SinacorComboBoxItem item in cbControlSelector.Items)
                {
                    switch (ComboSelection.Value)
                    {
                        case SelectionComboType.CPF:
                            if (item.Name == "cbItemCPF")
                                cbControlSelector.SelectedItem = item;
                            break;
                        case SelectionComboType.CNPJ:
                            if (item.Name == "cbItemCNPJ")
                                cbControlSelector.SelectedItem = item;
                            break;
                        case SelectionComboType.CVM:
                            if (item.Name == "cbItemCVM")
                                cbControlSelector.SelectedItem = item;
                            break;
                        case SelectionComboType.ClienteEstrangeiro:
                            if (item.Name == "cbItemClienteEstrangeiro")
                                cbControlSelector.SelectedItem = item;
                            break;
                        case SelectionComboType.Outros:
                            if (item.Name == "cbItemOutros")
                                cbControlSelector.SelectedItem = item;
                            break;
                        default:
                            cbControlSelector.SelectedIndex = -1;
                            break;
                    }
                }

            cbControlSelector.SelectionChanged += new SelectionChangedEventHandler(cbControlSelector_SelectionChanged);

            this.HideTextBoxes();
            //CreateValidations();

            EventValidationTrigger trigger = new EventValidationTrigger(ValidationTriggerScope.Self, LostFocusEvent);
            trigger.ContinueRoutingOnError = true;
            if (!this.ValidationTriggers.Contains(trigger))
                this.ValidationTriggers.Add(trigger);

            //Binding bdIsCnpjReadOnly = new Binding("IsCnpjReadOnly");
            //bdIsCnpjReadOnly.Mode = BindingMode.TwoWay;
            //bdIsCnpjReadOnly.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //this.txtCNPJ.SetBinding(SinacorCnpjTextBox.IsReadOnlyProperty, bdIsCnpjReadOnly);

            //Binding bdIsCpfReadOnly = new Binding("IsCpfReadOnly");
            //bdIsCpfReadOnly.Mode = BindingMode.TwoWay;
            //bdIsCpfReadOnly.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //this.txtCPF.SetBinding(SinacorCpfTextBox.IsReadOnlyProperty, bdIsCpfReadOnly);

            //Binding bdIsCvmReadOnly = new Binding("IsCvmReadOnly");
            //bdIsCvmReadOnly.Mode = BindingMode.TwoWay;
            //bdIsCvmReadOnly.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //this.txtCVM.SetBinding(SinacorCvmTextBox.IsReadOnlyProperty, bdIsCvmReadOnly);

            //Binding bdIsClienteEstrangeiroReadOnly = new Binding("IsClienteEstrangeiroReadOnly");
            //bdIsClienteEstrangeiroReadOnly.Mode = BindingMode.TwoWay;
            //bdIsClienteEstrangeiroReadOnly.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //this.txtClienteEstrangeiro.SetBinding(SinacorInvestidorEstrangeiroTextBox.IsReadOnlyProperty, bdIsClienteEstrangeiroReadOnly);

            //Binding bdIsOutrosReadOnly = new Binding("IsOutrosReadOnly");
            //bdIsOutrosReadOnly.Mode = BindingMode.TwoWay;
            //bdIsOutrosReadOnly.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            //this.txtOutros.SetBinding(SinacorFilteredTextBox.IsReadOnlyProperty, bdIsOutrosReadOnly);

            //txtCNPJ.IsReadOnly = IsCnpjReadOnly;
            //txtCPF.IsReadOnly = IsCpfReadOnly;
            //txtCVM.IsReadOnly = IsCvmReadOnly;
            //txtClienteEstrangeiro.IsReadOnly = IsClienteEstrangeiroReadOnly;
            //txtOutros.IsReadOnly = IsOutrosReadOnly;            
        }

        void HideTextBoxes()
        {
            this.HideTextBoxes(cbControlSelector);
        }

        void HideTextBoxes(ComboBox cb)
        {
            if (externalCPFBinding == null)
                externalCPFBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CPFBindProperty);
            if (externalCVMBinding == null)
                externalCVMBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CVMBindProperty);
            if (externalCNPJBinding == null)
                externalCNPJBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.CNPJBindProperty);
            if (externalOutrosBinding == null)
                externalOutrosBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.OutrosBindProperty);
            if (externalClienteEstrangeiroBinding == null)
                externalClienteEstrangeiroBinding = BindingOperations.GetBinding(this, SinacorIdentificadorInvestidor.ClienteEstrangeiroBindProperty);

            txtClienteEstrangeiro.Visibility = Visibility.Collapsed;
            txtCNPJ.Visibility = Visibility.Collapsed;
            txtCPF.Visibility = Visibility.Collapsed;
            txtCVM.Visibility = Visibility.Collapsed;
            txtOutros.Visibility = Visibility.Collapsed;
            Binding bd = null;

            if (cb.SelectedItem != null)
            {
                if (cb.Items != null && cb.Items.Count > 0)
                {
                    ComboBoxItem cbItem = (ComboBoxItem)cb.SelectedItem;
                    switch (cbItem.Name)
                    {
                        case "cbItemCPF":
                            txtCPF.Visibility = Visibility.Visible;
                            txtCPF.IsEnabled = true;
                            if (this.ComboSelection != SelectionComboType.CPF)
                                this.ComboSelection = SelectionComboType.CPF;

                            ClearAllFields();
                            ClearAllBinds();

                            if (externalCPFBinding != null)
                                BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.CPFBindProperty, externalCPFBinding);

                            bd = new Binding("CPFBind");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                            //converter foi removido pois estava gerando efeitos colaterais na validacao
                            //bd.Converter = new CPFConverter();
                            bd.RelativeSource = RelativeSource.Self;
                            this.SetBinding(SinacorIdentificadorInvestidor.InternalCPFValueProperty, bd);

                            bd = new Binding("InternalCPFValue");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            bd.RelativeSource = RelativeSource.TemplatedParent;
                            this.txtCPF.SetBinding(SinacorCpfTextBox.ValueProperty, bd);
                            break;
                        case "cbItemCNPJ":
                            txtCNPJ.Visibility = Visibility.Visible;
                            txtCNPJ.IsEnabled = true;
                            if (this.ComboSelection != SelectionComboType.CNPJ)
                                this.ComboSelection = SelectionComboType.CNPJ;

                            ClearAllFields();
                            ClearAllBinds();

                            if (externalCNPJBinding != null)
                                BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.CNPJBindProperty, externalCNPJBinding);

                            bd = new Binding("CNPJBind");
                            bd.Mode = BindingMode.TwoWay;
                            //converter foi removido pois estava gerando efeitos colaterais na validacao    
                            //bd.Converter = new CNPJConverter();
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                            bd.RelativeSource = RelativeSource.Self;
                            this.SetBinding(SinacorIdentificadorInvestidor.InternalCNPJValueProperty, bd);

                            bd = new Binding("InternalCNPJValue");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            bd.RelativeSource = RelativeSource.TemplatedParent;
                            this.txtCNPJ.SetBinding(SinacorCnpjTextBox.ValueProperty, bd);
                            break;
                        case "cbItemCVM":
                            txtCVM.Visibility = Visibility.Visible;
                            txtCVM.IsEnabled = true;
                            if (this.ComboSelection != SelectionComboType.CVM)
                                this.ComboSelection = SelectionComboType.CVM;

                            ClearAllFields();
                            ClearAllBinds();

                            if (externalCVMBinding != null)
                                BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.CVMBindProperty, externalCVMBinding);

                            bd = new Binding("CVMBind");
                            bd.Mode = BindingMode.TwoWay;
                            //converter foi removido pois estava gerando efeitos colaterais na validacao    
                            //bd.Converter = new CVMConverter();
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                            bd.RelativeSource = RelativeSource.Self;
                            this.SetBinding(SinacorIdentificadorInvestidor.InternalCVMValueProperty, bd);

                            bd = new Binding("InternalCVMValue");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            bd.RelativeSource = RelativeSource.TemplatedParent;
                            this.txtCVM.SetBinding(SinacorCvmTextBox.ValueProperty, bd);
                            break;
                        case "cbItemClienteEstrangeiro":
                            txtClienteEstrangeiro.Visibility = Visibility.Visible;
                            txtClienteEstrangeiro.IsEnabled = true;
                            if (this.ComboSelection != SelectionComboType.ClienteEstrangeiro)
                                this.ComboSelection = SelectionComboType.ClienteEstrangeiro;

                            ClearAllFields();
                            ClearAllBinds();

                            if (externalClienteEstrangeiroBinding != null)
                                BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.ClienteEstrangeiroBindProperty, externalClienteEstrangeiroBinding);

                            bd = new Binding("ClienteEstrangeiroBind");
                            bd.Mode = BindingMode.TwoWay;
                            //converter foi removido pois estava gerando efeitos colaterais na validacao    
                            //bd.Converter = new ClienteEstrangeiroConverter();
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                            bd.RelativeSource = RelativeSource.Self;
                            this.SetBinding(SinacorIdentificadorInvestidor.InternalClienteEstrangeiroValueProperty, bd);

                            bd = new Binding("InternalClienteEstrangeiroValue");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            bd.RelativeSource = RelativeSource.TemplatedParent;
                            this.txtClienteEstrangeiro.SetBinding(SinacorInvestidorEstrangeiroTextBox.ValueProperty, bd);
                            break;
                        case "cbItemOutros":
                            txtOutros.Visibility = Visibility.Visible;
                            txtOutros.IsEnabled = true;
                            if (this.ComboSelection != SelectionComboType.Outros)
                                this.ComboSelection = SelectionComboType.Outros;

                            ClearAllFields();
                            ClearAllBinds();

                            if (externalOutrosBinding != null)
                                BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.OutrosBindProperty, externalOutrosBinding);

                            bd = new Binding("OutrosBind");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;
                            bd.RelativeSource = RelativeSource.Self;
                            this.SetBinding(SinacorIdentificadorInvestidor.InternalOutrosValueProperty, bd);

                            bd = new Binding("InternalOutrosValue");
                            bd.Mode = BindingMode.TwoWay;
                            bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                            bd.RelativeSource = RelativeSource.TemplatedParent;
                            this.txtOutros.SetBinding(SinacorFilteredTextBox.TextProperty, bd);
                            break;

                        //txtOutros.Visibility = Visibility.Visible;
                        //txtOutros.IsEnabled = true;
                        //if (this.ComboSelection != SelectionComboType.Outros)
                        //    this.ComboSelection = SelectionComboType.Outros;

                        //ClearAllFields();
                        //ClearAllBinds();

                        //if (externalOutrosBinding != null)
                        //    BindingOperations.SetBinding(this, SinacorIdentificadorInvestidor.OutrosBindProperty, externalOutrosBinding);

                        //bd = new Binding("OutrosBind");
                        //bd.Mode = BindingMode.TwoWay;
                        //bd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                        //bd.RelativeSource = RelativeSource.TemplatedParent;
                        //this.txtOutros.SetBinding(SinacorFilteredTextBox.TextProperty, bd);
                        //break;
                        default:
                            if (this.ComboSelection != null)
                                this.ComboSelection = null;
                            break;
                    }
                }
            }
            else
            {
                txtOutros.Visibility = Visibility.Visible;
                txtOutros.IsEnabled = false;
                this.ComboSelection = null;
                ClearAllFields();
            }
        }

        void ClearAllBinds()
        {
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.CPFBindProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.ClienteEstrangeiroBindProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.CNPJBindProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.CVMBindProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.OutrosBindProperty);

            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.InternalClienteEstrangeiroValueProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.InternalCPFValueProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.InternalCNPJValueProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.InternalCVMValueProperty);
            BindingOperations.ClearBinding(this, SinacorIdentificadorInvestidor.InternalOutrosValueProperty);
        }

        void cbControlSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox)
            {
                if (e.RemovedItems.Count > 0)
                    this.ClearAllFields2();

                this.HideTextBoxes(sender as ComboBox);
            }

            if (e.RemovedItems.Count > 0)
            {
                if (this.ComboSelection == SelectionComboType.ClienteEstrangeiro)
                    txtClienteEstrangeiro.Clear();
                if (this.ComboSelection == SelectionComboType.CNPJ)
                    txtCNPJ.Clear();
                if (this.ComboSelection == SelectionComboType.CPF)
                    txtCPF.Clear();
                if (this.ComboSelection == SelectionComboType.CVM)
                    txtCVM.Clear();
                if (this.ComboSelection == SelectionComboType.Outros)
                    txtOutros.Clear();
            }
        }

        void ClearAllFields()
        {
            if (this.ComboSelection != SelectionComboType.ClienteEstrangeiro)
            {
                txtClienteEstrangeiro.Clear();

                BindingExpression be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalClienteEstrangeiroValueProperty);
                if (be != null)
                    be.UpdateSource();
            }
            if (this.ComboSelection != SelectionComboType.CNPJ)
            {
                txtCNPJ.Clear();

                BindingExpression be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCNPJValueProperty);
                if (be != null)
                    be.UpdateSource();
            }
            if (this.ComboSelection != SelectionComboType.CPF)
            {
                txtCPF.Clear();

                BindingExpression be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCPFValueProperty);
                if (be != null)
                    be.UpdateSource();

            }
            if (this.ComboSelection != SelectionComboType.CVM)
            {
                txtCVM.Clear();

                BindingExpression be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCVMValueProperty);
                if (be != null)
                    be.UpdateSource();

            }
            if (this.ComboSelection != SelectionComboType.Outros)
            {
                txtOutros.Clear();

                BindingExpression be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalOutrosValueProperty);
                if (be != null)
                    be.UpdateSource();
            }
        }

        void ClearAllFields2()
        {
            BindingExpression be;

            //if (this.ComboSelection != SelectionComboType.ClienteEstrangeiro)
            //{
            txtClienteEstrangeiro.Clear();
            ClienteEstrangeiroBind = null;

            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalClienteEstrangeiroValueProperty);
            if (be != null)
                be.UpdateSource();
            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.ClienteEstrangeiroBindProperty);
            if (be != null)
                be.UpdateSource();
            //}
            //if (this.ComboSelection != SelectionComboType.CNPJ)
            //{
            txtCNPJ.Clear();
            CNPJBind = null;

            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCNPJValueProperty);
            if (be != null)
                be.UpdateSource();
            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.CNPJBindProperty);
            if (be != null)
                be.UpdateSource();
            //}
            //if (this.ComboSelection != SelectionComboType.CPF)
            //{
            txtCPF.Clear();
            CPFBind = null;

            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCPFValueProperty);
            if (be != null)
                be.UpdateSource();
            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.CPFBindProperty);
            if (be != null)
                be.UpdateSource();

            //}
            //if (this.ComboSelection != SelectionComboType.CVM)
            //{
            txtCVM.Clear();
            CVMBind = null;

            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalCVMValueProperty);
            if (be != null)
                be.UpdateSource();
            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.CVMBindProperty);
            if (be != null)
                be.UpdateSource();

            //}
            //if (this.ComboSelection != SelectionComboType.Outros)
            //{
            txtOutros.Clear();
            OutrosBind = null;

            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.InternalOutrosValueProperty);
            if (be != null)
                be.UpdateSource();
            be = this.GetBindingExpression(SinacorIdentificadorInvestidor.OutrosBindProperty);
            if (be != null)
                be.UpdateSource();
            //}
        }

        #region IValidatable Members

        public static readonly DependencyProperty CanValidateProperty = ValidationManager.CanValidateProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Indica se o objeto suporta validação
        /// </summary>
        public bool CanValidate
        {
            get { return (bool)GetValue(CanValidateProperty); }
        }

        public static readonly DependencyProperty ValidationGroupProperty = ValidationManager.ValidationGroupProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Grupo de validação do objeto, informar null ou string.Empty nos objetos que disparam 
        /// validação para ignorar o grupo de validação
        /// </summary>
        public string ValidationGroup
        {
            get { return (string)GetValue(ValidationGroupProperty); }
            set { SetValue(ValidationGroupProperty, value); }
        }
        #endregion

        #region IValidatableObject Members

        public static readonly DependencyProperty ClearServiceErrorsProperty = ValidationManager.ClearServiceErrorsProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Indica se o objeto dispara validação
        /// </summary>
        public bool ClearServiceErrors
        {
            get { return (bool)GetValue(ClearServiceErrorsProperty); }
            set { SetValue(ClearServiceErrorsProperty, value); }
        }

        public static readonly DependencyProperty CausesValidationProperty = ValidationManager.CausesValidationProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Indica se o objeto dispara validação
        /// </summary>
        public bool CausesValidation
        {
            get { return (bool)GetValue(CausesValidationProperty); }
            set { SetValue(CausesValidationProperty, value); }
        }

        public static readonly DependencyProperty ValidationTriggersProperty = ValidationManager.ValidationTriggersProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Triggers que disparam a validação do objeto
        /// </summary>
        public ValidationTriggerCollection ValidationTriggers
        {
            get { return (ValidationTriggerCollection)GetValue(ValidationTriggersProperty); }
        }

        public static readonly DependencyProperty ValidationRulesProperty = ValidationManager.ValidationRulesProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Regras de validação do objeto
        /// </summary>
        public ValidationRuleCollection ValidationRules
        {
            get { return (ValidationRuleCollection)GetValue(ValidationRulesProperty); }
        }

        public static readonly DependencyProperty HasErrorProperty = ValidationManager.HasErrorProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));
        /// <summary>
        /// Indica se objeto tem erros
        /// </summary>
        public bool HasError
        {
            get { return (bool)GetValue(HasErrorProperty); }
        }

        public static readonly DependencyProperty ErrorsProperty = ValidationManager.ErrorsProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));

        /// <summary>
        /// Erros do objeto
        /// </summary>
        public ReadOnlyObservableCollection<ValidationError> Errors
        {
            get { return (ReadOnlyObservableCollection<ValidationError>)GetValue(ErrorsProperty); }
        }

        public static readonly DependencyProperty ErrorTemplateProperty = ValidationManager.ErrorTemplateProperty.AddOwner(typeof(SinacorIdentificadorInvestidor));

        /// <summary>
        /// Template aplicado quando objeto tem erros
        /// </summary>
        public ControlTemplate ErrorTemplate
        {
            get { return (ControlTemplate)GetValue(ErrorTemplateProperty); }
            set { SetValue(ErrorTemplateProperty, value); }
        }

        /// <summary>
        /// Valida todas as properties do objeto
        /// </summary>
        /// <returns>True se todas as properties forem válidas</returns>
        public bool Validate()
        {
            return ValidationManager.Validate(this) && ValidationManager.Validate(this.txtCPF) && ValidationManager.Validate(this.txtCNPJ) && ValidationManager.Validate(this.txtCVM) && ValidationManager.Validate(this.txtClienteEstrangeiro) && ValidationManager.Validate(this.txtOutros);
        }

        /// <summary>
        /// Valida a property informada do objeto
        /// </summary>
        /// <param name="property">Property a ser validada</param>
        /// <returns>True se a property for válida</returns>
        public bool Validate(DependencyProperty property)
        {
            return ValidationManager.Validate(this, property);
        }

        /// <summary>
        /// Valida todos os objetos do container pai do objeto
        /// </summary>
        /// <returns>True se todos os objetos forem válidos</returns>
        public bool ValidateParentContainer()
        {
            return ValidationManager.ValidateParentContainer(this);
        }

        #endregion

        #region IVisibilityBehaviorPolicy Members

        bool IVisibilityBehaviorPolicy.IsVisible
        {
            get
            {
                return this.Visibility == Visibility.Visible;
            }
            set
            {
                this.Visibility = (value ? Visibility.Visible : Visibility.Collapsed);
            }
        }

        #endregion

        #region IBehaviorPolicyObject Members

        public string PolicyName
        {
            get
            {
                return (string)GetValue(PolicyNameProperty);
            }
            set
            {
                SetValue(PolicyNameProperty, value);
            }
        }

        #endregion

        #region IVisibilityBehaviorPolicy Members


        public string PropertyName
        {
            get { return "Visibility"; }
        }

        #endregion

        #region IBehaviorPolicyObject Members

        string IBehaviorPolicyObject.PolicyName
        {
            get
            {
                return (string)GetValue(PolicyNameProperty);
            }
            set
            {
                SetValue(PolicyNameProperty, value);
            }
        }

        #endregion

        #region INotifyPropertyChanged Members
        /// <summary>
        /// Evento da propriedade ao mudar a visibilidade
        /// </summary>
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        #endregion

        void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }

        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            OnPropertyChanged(e.Property.Name);

            if (e.Property.Name == "ComboSelection")
            {
                bool foundIt = false;

                if (cbControlSelector != null)
                {
                    if (ComboSelection != null)
                    {
                        foreach (SinacorComboBoxItem item in cbControlSelector.Items)
                        {
                            switch (ComboSelection.Value)
                            {
                                case SelectionComboType.CPF:
                                    if (item.Name == "cbItemCPF")
                                        foundIt = true;
                                    break;
                                case SelectionComboType.CNPJ:
                                    if (item.Name == "cbItemCNPJ")
                                        foundIt = true;
                                    break;
                                case SelectionComboType.CVM:
                                    if (item.Name == "cbItemCVM")
                                        foundIt = true;
                                    break;
                                case SelectionComboType.ClienteEstrangeiro:
                                    if (item.Name == "cbItemClienteEstrangeiro")
                                        foundIt = true;
                                    break;
                                case SelectionComboType.Outros:
                                    if (item.Name == "cbItemOutros")
                                        foundIt = true;
                                    break;
                            }

                            if (foundIt)
                            {
                                cbControlSelector.SelectedValue = item;
                                this.HideTextBoxes();
                                break;
                            }
                        }
                    }
                    else
                    {
                        cbControlSelector.SelectedIndex = -1;
                    }
                }
            }
        }

        protected override void OnVisualParentChanged(DependencyObject oldParent)
        {
            base.OnVisualParentChanged(oldParent);
            TemplateHelper.ApplyGridTemplate(this);
        }

        public class CPFConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 11)
                    return ((string)value).PadLeft(11, '0');
                return "";
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 11)
                    return ((string)value).PadLeft(11, '0');
                else
                    return "";
            }
        }

        public class CNPJConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 14)
                    return ((string)value).PadLeft(14, '0');
                return "";
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 14)
                    return ((string)value).PadLeft(14, '0');
                return "";
            }
        }

        public class CVMConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 19)
                    return ((string)value).PadLeft(19, '0');
                return "";
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 19)
                    return ((string)value).PadLeft(19, '0');
                return "";
            }
        }

        public class ClienteEstrangeiroConverter : IValueConverter
        {
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 15)
                    return ((string)value).PadLeft(15, '0');
                return "";
            }
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (!String.IsNullOrEmpty((string)value) && ((string)value).Length <= 15)
                    return ((string)value).PadLeft(15, '0');
                return "";
            }
        }
    }
}
